package common.configuration;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.net.InetAddress;
import java.util.Properties;

import se.sics.kompics.address.Address;

public final class ControlConfiguration {
	private final Address controlServerAddress;

//-------------------------------------------------------------------
	public ControlConfiguration(Address controlServerAddress) {
		super();
		this.controlServerAddress = controlServerAddress;
	}

//-------------------------------------------------------------------
	public Address getControlServerAddress() {
		return this.controlServerAddress;
	}
	
//-------------------------------------------------------------------
	public void store(String file) throws IOException {
		Properties p = new Properties();
		p.setProperty("server.ip", ""
				+ controlServerAddress.getIp().getHostAddress());
		p.setProperty("control.port", "" + controlServerAddress.getPort());
		p.setProperty("control.id", "" + controlServerAddress.getId());
		Writer writer = new FileWriter(file);
		p.store(writer, "se.sics.kompics.p2p.control");
	}

//-------------------------------------------------------------------
	public static ControlConfiguration load(String file) throws IOException {
		Properties p = new Properties();
		Reader reader = new FileReader(file);
		p.load(reader);
		InetAddress ip = InetAddress.getByName(p.getProperty("control.ip"));
		int port = Integer.parseInt(p.getProperty("control.port"));
		int id = Integer.parseInt(p.getProperty("control.id"));

		Address controlServerAddress = new Address(ip, port, id);

		return new ControlConfiguration(controlServerAddress);
	}
}
